package com.sybil.spa.dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Transactional("transactionManagerR12")
public abstract class AbstractDAOr12<E, PK extends Serializable> {

   private final Class<E> claseEntidad;

   @Autowired
   private SessionFactory sessionFactoryR12;

   public AbstractDAOr12(Class<E> claseEntidad) {
      this.claseEntidad = claseEntidad;
   }

   protected Session sesionActual() {
      return sessionFactoryR12.getCurrentSession();
   }

   protected Criteria getCriteria() {
      return sesionActual().createCriteria(claseEntidad);
   }

   protected List<E> obtener() {
      return sesionActual().createCriteria(claseEntidad).list();
   }

   protected E obtener(PK pk) {
      return (E) sesionActual().get(claseEntidad, pk);
   }

   protected List<E> obtener(Criterion criterion) {
      Criteria c = getCriteria();
      c.add(criterion);
      return c.list();
   }

   protected void guardar(E e) {
      Session session = sessionFactoryR12.openSession();
      try {
         session.beginTransaction();
         session.save(e);
         session.getTransaction().commit();
      } catch (HibernateException ex) {
         session.getTransaction().rollback();
         throw ex;
      } finally {
         session.close();
      }
   }

   protected void editar(E e) {
      Session session = sessionFactoryR12.openSession();
      try {
         session.beginTransaction();
//         session.update(e);
         session.merge(e);
         session.getTransaction().commit();
      } catch (HibernateException ex) {
         session.getTransaction().rollback();
         throw ex;
      } finally {
         session.close();
      }
   }

   protected void eliminar(E e) {
      sesionActual().delete(e);
   }
}
